﻿module fs.Office
open fs
open Base
open File
module Excel =
    open System.Data
    open System.Data.OleDb
    let listSheets (c: OleDbConnection) = c.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows |> Seq.cast<DataRow> |> Seq.map (fun a -> (string a.["Table_Name"]))
//                let r = c.GetOleDbSchemaTable(OleDbSchemaGuid .Tables, null)
//                if r <> null then r.Rows |> Seq.cast<DataRow> |> Seq.map (fun a -> string a.["TABLE_NAME"]) else failwith ""
    let getSet c =
        let fillTable a (c: OleDbConnection) (r: DataSet) = (new OleDbDataAdapter(sprintf "select * from [%s]" a, c)).Fill(r, a) |> ignore
        let r = new DataSet()
        listSheets c |> Seq.iter (fun a -> try fillTable a c r with :? OleDbException -> () |> ignore)
        r
//            let s = listSheets c |> Seq.head
//            let q = sprintf "select * from [%s]" s
////            let q = "select * from ['4月搬运工$']"
//            (new OleDbDataAdapter(q, c)).Fill r |> ignore; r
//        let schemaGuids (c: OleDbConnection) =
//            let guids = c.GetOleDbSchemaTable(OleDbSchemaGuid.SchemaGuids, null).Rows |> Seq.cast<DataRow> |> Seq.map (fun a -> Guid (string a.["Schema"]))
//            let names = typeof<OleDbSchemaGuid>.GetFields() |> Seq.map (fun a -> a.Name, a.GetValue() :?> Guid) |> Seq.filter (fun a -> not (["Columns"; "Views"] |> Seq.exists (fun b -> b = fst a)))
////            let map g =
////                let r = names |> Seq.tryFind (fun a -> snd a = g)
////                if isSome r then fst (get r) else Guid.toString g
//            guids |> Seq.filter (fun a -> names |> Seq.exists (fun b -> snd b = a))
//        let getSchema (c: OleDbConnection) =
//            let r = new DataSet()
//            schemaGuids c |> Seq.choose (fun a -> try Some (c.GetOleDbSchemaTable(a, null)) with :? OleDbException -> None) |> Seq.iter (fun a -> r.Tables.Add a)
//            r
    module File =
        let makeConnection file =
//                let c = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" + file + "\";Extended Properties=\"Excel 8.0\"")
            let c = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + file + ";Extended Properties=\"Excel 12.0;IMEX=1\"")
            c.Open(); c
        let listSheets file = makeConnection file |> listSheets
        let getSet file = makeConnection file |> getSet
//            let schemaGuids file = makeConnection file |> schemaGuids
////            let listSchemaGuids file = makeConnection file |> listSchemaGuids
//            let getSchema file = makeConnection file |> getSchema
module File=
    open File
    module Word =
//            open System.Drawing.Printing
//            open System.Diagnostics
        open Microsoft.Office.Interop.Word
//            open Web.HttpContext.Current.Server
//            let virtualPrint file =
//                let d = new PrintDocument (PrinterSettings = PrinterSettings (PrinterName = "Zan Image Printer (Color)", MaximumPage = 1))
//                let p = new Process (StartInfo = ProcessStartInfo (CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Normal, UseShellExecute = true, FileName = file, Verb = "print", Arguments = d.PrinterSettings.PrinterName + string d.PrinterSettings.MaximumPage))
//                p.Start() |> ignore
//                p.Exited.Add(fun e ->
//                    let g = Guid.NewGuid()
////                    let dirPath = mapPath "~/DocImg/" + Guid.toString g
////                    if not (Directory.exists dirPath) then Directory.create dirPath
////                    for fi in Directory.getFiles "~/DocImgTemp" do move fi (Path.combine dirPath fi))
//                    g |> ignore)
        let printWith file printer =
            let w = ApplicationClass (ActivePrinter = printer.Name)
//                w.Visible <- true
            let file2 = ref (file :> obj)
            let d = w.Documents.Open (file2)
            d.PrintOut()
            d.Close()
            w.Quit()
        module ConvertTo =
            let Tiff (wordFilePath, mdifFilePath, width, height) = //,String tifAddress
                let w = ApplicationClass (ActivePrinter = "Microsoft Office Document Image Writer") //设置Word的虚拟打印机 ImagePrinter
                let m = System.Reflection.Missing.Value :> obj
                let FileName = wordFilePath
                let ConfirmConversions = false :> obj
                let ReadOnly = true :> obj
                let AddToRecentFiles = true :> obj
                let PasswordDocument = false :> obj
                let PasswordTemplate = false :> obj
                let Revert = false :> obj
                let WritePasswordDocument = false :> obj
                let WritePasswordTemplate = false :> obj
                let Visible = false :> obj
                let OpenAndRepair = false :> obj
                let Background = false :> obj
                let Append = true :> obj
                let Range = WdPrintOutRange.wdPrintAllDocument :> obj
                let Copies = 1 :> obj
                let tiffFilePath = mdifFilePath :> obj
                //let dir = new DirectoryInfo(TiffFilePath);
                //let tiffFilePath = dir.FullName.Remove(dir.FullName.LastIndexOf("."));
                let OutputFileName = tiffFilePath
                let PageType = WdPrintOutPages.wdPrintAllPages
                let PrintToFile = true :> obj
                let Collate = true :> obj
                let PrintZoomColumn = 1 :> obj
                let PrintZoomRow = 1 :> obj
                let PrintZoomPaperWidth = width * 14.40 :> obj
                let PrintZoomPaperHeight = height * 14.40 :> obj
                let d = w.Documents.Open (ref FileName, ref ConfirmConversions, ref ReadOnly, ref AddToRecentFiles, ref m, ref m, ref Revert, ref m, ref m, ref m, ref m, ref Visible, ref OpenAndRepair, ref m, ref m, ref m)
                d.Activate() //激活文档
                d.PrintOut (ref m, ref m, ref m, ref OutputFileName, ref m, ref m, ref m, ref Copies, ref m, ref m, ref PrintToFile, ref Collate, ref m, ref m, ref PrintZoomColumn, ref PrintZoomRow, ref PrintZoomPaperWidth, ref PrintZoomPaperHeight)
                let saveChanges = WdSaveOptions.wdPromptToSaveChanges :> obj
                let originalFormat = WdOriginalFormat.wdWordDocument :> obj
                let routeDocument = false :> obj
                if (exists mdifFilePath) then
                    d.Close()
                    w.Quit()
        let createForGroupPrinting (filename: string) (imageFiles: seq<string>) =
            let m = System.Reflection.Missing.Value :> obj
//                let filename = @"e:\111.doc" :> obj
            //创建Word文档
            let w = ApplicationClass()
            w.Visible <- true
            let d = w.Documents.Add(ref m, ref m, ref m, ref m)

            d.PageSetup.TopMargin <- 0.0f
            d.PageSetup.RightMargin <- 0.0f
            d.PageSetup.BottomMargin <- 0.0f
            d.PageSetup.LeftMargin <- 0.0f

            let LinkToFile = false :> obj
            let SaveWithDocument = true :> obj
            let Anchor = d.Application.Selection.Range :> obj
            let filename2 = ref (filename + ".doc" :> obj)
            for i in imageFiles do d.Application.ActiveDocument.InlineShapes.AddPicture(i, ref LinkToFile, ref SaveWithDocument, ref Anchor) |> ignore
            d.SaveAs(filename2)
            d.Close()
            w.Quit()
    module Excel =
        open System.Drawing
        open Microsoft.Office.Interop.Excel
        let printWith file printer =
            let w = ApplicationClass ()
//                w.Visible <- true
//                let file2 = ref (file :> obj)
            let d = w.Workbooks.Open file
            let s = d.Sheets.[1] :?> Worksheet
            s.PrintOut()
            d.Close(false)
            w.Quit()
        let sortAndPrintWith file printer =
            let w = ApplicationClass ()
            w.Visible <- true
            let d = w.Workbooks.Open file
            let s = d.Sheets.[1] :?> Worksheet
            (s.Cells.[1, 4] :?> Range).EntireColumn.AutoFit() |> ignore
            let r = s.UsedRange
            r.Borders.Color <- Color.Black
            s.PageSetup.Zoom <- false
            s.PageSetup.FitToPagesWide <- 1
            s.PageSetup.Orientation <- XlPageOrientation.xlLandscape
            s.PrintOut()
            d.Close(false)
            w.Quit()
module ZanImagePrinter =
    open File
    let p = { Name = "Zan Image Printer (Color)" }
    let o = @"C:\t"
//    let printToPngFromPdf f =
//        Pdf.printWith f p
//        Directory.getFiles o |> Seq.filter (fun a -> a.Contains (Path.fileName f))
    let printToPngFromWord f =
        Word.printWith f p
        Directory.getFiles o |> Seq.filter (fun a -> a.Contains (Path.fileName f))
    let printToPngFromExcelSorted f =
        Excel.sortAndPrintWith f p
        Directory.getFiles o |> Seq.filter (fun a -> a.Contains (Path.fileName f))
    let printToPngFromExcel f =
        Excel.printWith f p
        Directory.getFiles o |> Seq.filter (fun a -> a.Contains (Path.fileName f))
//        let printFileToPng f =
//            if isWord f then Word.printWith f p
//            Directory.getFiles o
